import {Cell} from "./cell";
import {Fence} from "./fence";
import {Joiner} from "../../utils/joiner";

class SkuPending { //存储已选中的cell

    pending = []
    size

    constructor(size) {
        this.size = size
    }

    init(sku) {
        for (let i = 0; i < sku.specs.length; i++) {
            const cell = new Cell(sku.specs[i])
            this.insertCell(cell, i)
        }
    }

    getCurrentSpecValues() {
        return this.pending.map(cell => {
            return cell ? cell.spec.value : null
        })
    }

    getMissingSpecKeysIndex() {
        const keysIndex = []
        for (let i = 0; i < this.size; i++) {
            if (!this.pending[i]) {
                keysIndex.push(i)
            }
        }
        return keysIndex
    }

    getSkuCode() {
        if (!this.isIntact()) {
            return
        }
        return this.assembleSkuPath()
    }

    assembleSkuPath() {
        const joiner = new Joiner('#')
        this.pending.forEach(cell => {
            joiner.join(this._assembleCellCode(cell))
        })
        return joiner.getStr()
    }

    _assembleCellCode(cell) {
        const joiner = new Joiner()
        joiner.join(cell.spec.key_id)
        joiner.join(cell.spec.value_id)
        return joiner.getStr()
    }

    isIntact() {
        // if (this.size !== this.pending.length) {
        //     return false
        // }
        for (let i = 0; i < this.size; i++) {
            if (this._isEmptyPart(i)) {
                return false
            }
        }
        return true
    }

    _isEmptyPart(index) {
        return this.pending[index] ? false : true
    }

    insertCell(cell, x) {
        this.pending[x] = cell
    }

    //[undefined, undefined, cell] pending还没有存储到一个完整路径的时候的情况：也就是选择一个或两个规格的时候，这里选三个规格就组成一条完整路径

    removeCell(x) {
        this.pending[x] = null
    }

    findSelectedCellByX(x) {
        return this.pending[x]
    }

    isSelected(cell, x) {
        const pedingCell = this.pending[x]
        if (!pedingCell) {
            return false
        }
        return cell.id === pedingCell.id
    }

}

export {
    SkuPending
}